import jwt
from datetime import datetime, timedelta
import time

payload_data = {
    'user_id': 1,
    "exp": datetime.utcnow()+timedelta(seconds=3)
}

secret_key = 'abcdefg'
token = jwt.encode(payload_data, secret_key, algorithm='HS256')
print(token)
time.sleep(4)
ret_data = jwt.decode(token.decode(), secret_key, algorithms=['HS256'])
print(ret_data)

def generate_jwt(payload, expiry, secret):
    """
    封装生成token的函数
    :param payload:
    :param expiry:
    :param secret:
    :return:
    """
    _payload = payload
    _payload.update({'exp':expiry})
    token = jwt.encode(payload, secret, algorithm='HS256')
    return token.decode()

def verify_jwt(token, secret):
    """
    验证token
    :param token:
    :param secret:
    :return:
    """
    try :
        payload = jwt.decode(token, secret,algorithms='HS256')
    except:
        payload = None

    return payload
# 测试
payload_data = {
    'user_id' : 1
}
secret_key = "abcdefg"
expiry = datetime.utcnow()+timedelta(seconds=3)
token = generate_jwt(payload_data, expiry, secret_key)
print(token)

time.sleep(4)
ret_data = verify_jwt(token, secret_key)
print(ret_data)